﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Wicture.DbRESTFul.SQL;
using Wicture.EPC.Common;
using Wicture.EPC.Service.V1.Models;
using Wicture.EPC.Service.V1.Models.LiYang;
using Wicture.EPC.Service.V1.Repository;

namespace Wicture.EPC.Service.V1.QueryInterceptors.Interceptors
{
    public class TrumpchiQueryInterceptor : BaseQueryInterceptor
    {
        private readonly string[] brandCodes = new string[] { "trumpchi" };
        public override string[] BrandCodes => brandCodes;

        protected override List<Query_PartsResult> GetParts(DbRESTFulRepository repository, JObject param)
        {
            return repository.Invoke<Query_PartsResult>(CSIs.Query_Parts, param);
        }

        public override object QueryPartDetail(DbRESTFulRepository repository, JObject param)
        {
            param.RemoveEmptyValues();
            var brandCode = param.Value<string>(ParamFields._brandCode);
            var partId = param.Value<string>(ParamFields._partId);
            var partCode = param.Value<string>(ParamFields._partCode);
            dynamic data = null;

            if (string.IsNullOrEmpty(partId))
            {
                data = repository.Invoke(CSIs.Get_Part_Detail_Standard, new { partCode, brandCode });
            }
            else
            {
                data = repository.Invoke(CSIs.Get_Usage_Detail_For_Trumpchi, param);
            }
            if (data == null) return null;

            // 1、基本信息赋值
            Query_Part_DetailResult result = JObject.FromObject(data).ToObject<Query_Part_DetailResult>();

            result.replacements = new List<Query_Part_DetailResult._replacement>();
            //3.替换件处理
            if (!string.IsNullOrEmpty(result.replacementPartNo))
            {
                List<Query_Part_DetailResult._replacement> replacements = repository.Invoke<Query_Part_DetailResult._replacement>(CSIs.Query_Parts_By_Codes, new { partCodes = result.replacementPartNo.Split(',') });
                if (replacements != null)
                {
                    foreach (var replacement in replacements)
                    {
                        replacement.brandCode = brandCode;
                        replacement.brandName = BrandDictionary.GetName(brandCode);
                        result.replacements.Add(replacement);
                    }
                }
            }
            //4.配件附加属性处理
            var props = new List<Query_Part_DetailResult._prop>
            {
                new Query_Part_DetailResult._prop { key = "件数", value = result.quantity ?? string.Empty },
                new Query_Part_DetailResult._prop { key = "备注", value = data.modelNotes ?? string.Empty },
            };
            string notes = data.notes;
            if (!string.IsNullOrEmpty(notes))
            {
                string modelCode = data.modelCode;
                IEnumerable<Feature> features = repository.Invoke<Feature>(CSIs.Get_Features_For_Trumpchi, new { modelCode, featureCodes = notes.Split(',') });
                props.AddRange(features.Select(q => new Query_Part_DetailResult._prop
                {
                    key = q.featureCode,
                    value = q.featureName
                }));
            }
            result.props = props.Where(q => !string.IsNullOrEmpty(q.value)).ToList();
            return result;
        }

        protected override List<Query_SubGroupResult> BuildSubGroupResults(List<Query_SubGroupResult> result)
        {
            return result.OrderBy(q => q.code.Length).ThenBy(q => q.code).ToList();
        }
        protected override dynamic GetModelsByPart(DbRESTFulRepository repository, int pageIndex, int pageSize, string brandCode, string partCode)
        {
            return repository.Invoke(CSIs.Query_Models_By_Part_For_Trumpchi, new { pageIndex, pageSize, brandCode, partCode });
        }

        /// <summary>
        /// 根据力洋车型获取epc车型
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public override object ModelSelectorByLiYang(DbRESTFulRepository repository, JObject param)
        {
            Get_Model_InfoResult result = null;
            Get_Model_InfoResult._MultiModel multiModel = null;
            LiYangInfo info = param.ToObject<LiYangInfo>();

            string vin = info.vin;
            var liyangVinInfo = repository.Invoke(CSIs.Get_LiYang_Vin, new { vin });
            if (liyangVinInfo != null)
            {
                LiYangInfo liyangData = JsonConvert.DeserializeObject<LiYangInfo>(liyangVinInfo.liyangData);
                liyangData.vin = info.vin;
                liyangData.selectorId = info.selectorId;
                info = liyangData;
            }

            List<Get_Model_InfoResult> list = new List<Get_Model_InfoResult>();
            if (string.IsNullOrEmpty(info.selectorId))
            {
                list = repository.Invoke<Get_Model_InfoResult>(CSIs.Query_Model_By_LiYang_For_Trumpchi, new { year = info.Year, engineModel = info.EngineModel, manufacturers = info.Manufacturers, series = info.Series, models = info.Models });
            }
            else
            {
                list = repository.Invoke<Get_Model_InfoResult>(CSIs.Query_Model_By_LiYang_For_Trumpchi, new { year = info.Year, engineModel = info.EngineModel, manufacturers = info.Manufacturers, series = info.Series, models = info.Models, selectorId = info.selectorId });
            }

            if (list != null && list.Any())
            {
                result = list.ElementAt(0);
                result.vin = vin;
                if (list.Count() > 1)
                {
                    multiModel = new Get_Model_InfoResult._MultiModel
                    {
                        title = "选择配置",
                        param = new List<string> { "selectorId" },
                        header = new List<Get_Model_InfoResult._props> { new Get_Model_InfoResult._props { key = "engine", value = "发动机" }, new Get_Model_InfoResult._props { key = "transGrade", value = "变速器" } },
                        content = list.Select(q => new Get_Model_InfoResult._MultiModel._content { engine = q.engine, transGrade = q.transmission, selectorId = q.selectorId }).ToList()
                    };
                    result.multiModel = multiModel;
                }
                else
                {
                    result.warning = "注意：此车架号只解析到车型，请仔细核对";
                }
                result.props = GetProps(info, result.name);
            }
            return result;
        }
        private List<Get_Model_InfoResult._props> GetProps(LiYangInfo param, string epcModelName)
        {
            List<Get_Model_InfoResult._props> features = new List<Get_Model_InfoResult._props>();
            features.Add(new Get_Model_InfoResult._props { key = "车型", value = epcModelName });
            features.Add(new Get_Model_InfoResult._props { key = "年款", value = param.Year });
            features.Add(new Get_Model_InfoResult._props { key = "排放标准", value = param.EmissionStandard });
            features.Add(new Get_Model_InfoResult._props { key = "发动机型号", value = param.EngineModel });
            features.Add(new Get_Model_InfoResult._props { key = "变速器", value = param.TransmissionDescription });
            features.Add(new Get_Model_InfoResult._props { key = "排量", value = $"{param.Displacement} {param.Induction}" });
            features.Add(new Get_Model_InfoResult._props { key = "驱动", value = param.DriveMode });
            return features;
        }

        protected override List<Query_SubGroupResult> FilterSubGroupsByVin(DbRESTFulRepository repository, List<Query_SubGroupResult> results, JObject param)
        {
            return results;
        }
        protected override void FilterPartsByVin(DbRESTFulRepository repository, ref List<Query_PartsResult> result, string vin, string selectorId)
        {
        }
    }
}
